package com.train.trainmanage.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.Arrays;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.train.trainmanage.model.ComeGoDirectionModel;
import com.train.trainmanage.model.DepartmentModel;
import com.train.trainmanage.model.RelationDirectionModel;
import com.train.trainmanage.model.StationModel;
import com.train.trainmanage.model.TrackModel;
import com.train.trainmanage.model.TrainModel;
import com.train.trainmanage.model.UserModel;
import com.train.trainmanage.service.ComeGoDirectionService;
import com.train.trainmanage.service.DepartmentService;
import com.train.trainmanage.service.RelationDirectionService;
import com.train.trainmanage.service.StationService;
import com.train.trainmanage.service.TrackService;
import com.train.trainmanage.service.TrainService;
import com.train.trainmanage.util.ExcelUtil;



@RestController
@RequestMapping("/train")
public class TrainController {
	
	private static final Logger logger = LoggerFactory.getLogger(TrainController.class);
	
	@Autowired
	private TrainService trainService;
	@Autowired
	private TrackService trackService;
	@Autowired
	private StationService stationService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired 
	private ComeGoDirectionService comeGoService;
	@Autowired
	private RelationDirectionService relationDirectionService;
	
	
	
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response,TrainModel train) throws IOException, ParseException {
		ModelAndView mav = new ModelAndView();
		mav.addObject("menuId", "1");
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		if(user != null ) {
			Integer role = user.getRole();
			if(role != null && role.equals(2)) { //2:管理员
				logger.info("管理员---" + user.getUserName() + "----进入管理页面");
				//return "redirect:/personal/personal";
				response.sendRedirect(request.getContextPath() + "/train/manageList");   
			}else if(role != null && role.equals(1)) { //1:操作员
				logger.info("操作员---" + user.getUserName() + "进入管理页面");
				response.sendRedirect(request.getContextPath() + "/dailyPlan/workList");
			}else if(role != null && role.equals(3)) { //3:客运工作人员
				logger.info("客运工作人员---" + user.getUserName() + "进入管理页面");
				response.sendRedirect(request.getContextPath() + "/dailyPlan/workLookList");
			}else {
				response.sendRedirect(request.getContextPath() + "/user/login");
			}
		}else {
			response.sendRedirect(request.getContextPath() + "/user/login");
		}
		return mav;
	}
	
	@RequestMapping("/manageList")
	public ModelAndView manageList(HttpServletRequest request, HttpServletResponse response,TrainModel train,Integer pageNo) throws IOException, ParseException {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		mav.addObject("menuId", "1");
		logger.info(user.getUserName() + "进入管理列表页面");
		if(pageNo != null && pageNo >1) {
			train.setPageNo(pageNo);
		}
		
		List<TrainModel> trainList = trainService.listByTrainModel(train);
		Integer recordTotal = trainService.getCountByTrain(train);
		if(recordTotal > 0) {
			train.setRecordTotal(recordTotal);
			Integer temTotal = recordTotal / train.getPageSize();
			if(recordTotal % train.getPageSize() >0) {
				temTotal+=1;
			}
			train.setPageTotal(temTotal);
		}
		mav.addObject("trainList", trainList);
		mav.addObject("train", train);
		mav.setViewName("/train/manage");
		return mav;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("--------" + user.getUserName() +"----进入车次新增页面-------");
		List<DepartmentModel> departmentList = departmentService.allDepartmentList();
		
		List<TrackModel> trackList = trackService.listAllTrack();
		
		List<StationModel> stationList = stationService.getAllStation();
		
		List<ComeGoDirectionModel> comeDirectionList = comeGoService.listByType(1);
		
		List<ComeGoDirectionModel> goDirectionList = comeGoService.listByType(2);
		
		mav.addObject("departmentList", departmentList);
		mav.addObject("trackList", trackList);
		mav.addObject("stationList", stationList);
		mav.addObject("comeDirectionList", comeDirectionList);
		mav.addObject("goDirectionList", goDirectionList);
		mav.setViewName("/train/editTrain");
		return mav;
	}
	
	
	@RequestMapping("/edit")
	public ModelAndView update(HttpServletRequest request, HttpServletResponse response,Integer trainId) throws IOException {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("--------" + user.getUserName() +"------进入车次编辑页面-------");
		TrainModel train = new TrainModel();
		if(trainId != null && trainId > 0) {
			train = trainService.selectById(trainId);
		}
		
		//List<DepartmentModel> departmentList = departmentService.allDepartmentList();
		List<TrackModel> trackList = trackService.listAllTrack();
		List<StationModel> stationList = stationService.getAllStation();
		List<ComeGoDirectionModel> comeDirectionList = comeGoService.listByType(1);
		List<ComeGoDirectionModel> goDirectionList = comeGoService.listByType(2);
		
		mav.addObject("train", train);
		//mav.addObject("departmentList", departmentList);
		mav.addObject("trackList", trackList);
		mav.addObject("stationList", stationList);
		mav.addObject("comeDirectionList", comeDirectionList);
		mav.addObject("goDirectionList", goDirectionList);
		
		mav.setViewName("/train/editTrain");
		return mav;
	}
	
	
 	@RequestMapping("/save")
    public @ResponseBody Map<String, Object> saveTrain(HttpServletRequest httpRequest, HttpServletResponse httpResponse,TrainModel train,
    		String startTimeStr,String endTimeStr,String reachTimeStr,String leaveTimeStr) {
 		Map<String, Object> map = new HashMap<String, Object>();
	    logger.info("---------保存编辑后的车次信息-------");
	    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		  try {
			  if(startTimeStr != null && !"".equals(startTimeStr)) {
				  train.setStartTime(sdf.parse(startTimeStr));
			  }
			  if(endTimeStr != null && !"".equals(endTimeStr)) {
				  train.setEndTime(sdf.parse(endTimeStr));
			  }
			  if(reachTimeStr != null && !"".equals(reachTimeStr)) {
				  train.setReachTime(sdf.parse(reachTimeStr));
			  }
			  if(leaveTimeStr != null && !"".equals(leaveTimeStr)) {
				  train.setLeaveTime(sdf.parse(leaveTimeStr));
			  }
		} catch (ParseException e) {
			e.printStackTrace();
		}
	  
		Integer comeDirectionId = train.getComeDirectionId();
		Integer goDirectionId = train.getGoDirectionId();
		List<Integer> goIdList = relationDirectionService.listGoIdByComeId(comeDirectionId);
		if(goIdList != null && goIdList.size() > 0) {
			if(!goIdList.contains(goDirectionId)) {
				map.put("success", false);
				map.put("message", "来车方向，发车方向不匹配，请确认后再保存");
				return map;
			}
		}
		
		Integer pickUpTrack = train.getPickUpTrack();
		train.setDepartureTrack(pickUpTrack);
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("comeId", comeDirectionId);
		map2.put("goId", 0);
		RelationDirectionModel comeDirection = relationDirectionService.getByMap(map2);
		if(comeDirection != null) {
			String ableTrackString = comeDirection.getAbleTrace();
			if(ableTrackString != null && !ableTrackString.contains(pickUpTrack.toString())) {
				map.put("success", false);
				map.put("message", "所选来车方向，股道不匹配，请确认后再保存");
				return map;
			}
		}
		map2.clear();
		map2.put("comeId", comeDirectionId);
		map2.put("goId", goDirectionId);
		RelationDirectionModel goDirection = relationDirectionService.getByMap(map2);
		if(goDirection != null) {
			String ableTrackString = goDirection.getAbleTrace();
			if(ableTrackString != null && !ableTrackString.contains(pickUpTrack.toString())) {
				map.put("success", false);
				map.put("message", "所选发车方向，股道不匹配，请确认后再保存");
				return map;
			}
		}  
		TrackModel track = trackService.getByTrackId(pickUpTrack);
		Integer isAddWater = train.getIsAddWater();
		Integer isDealRubbish = train.getIsDealRubbish();
		if(track != null && track.getIsAddWater() != null) {
			if("1".equals(isAddWater.toString()) && !"1".equals(track.getIsAddWater().toString())) {
				map.put("success", false);
				map.put("message", "所选股道不支持上水，请确认后再保存");
				return map;
			}
		}
		if(track != null && track.getIsDealRubbish() != null) {
			if("1".equals(isDealRubbish.toString()) && !"1".equals(track.getIsDealRubbish().toString())) {
				map.put("success", false);
				map.put("message", "所选股道不支持去污，请确认后再保存");
				return map;
			}
		}
	   int result = 0;
	   if(train != null) {
		   Integer trainId = train.getTrainId();
		   if(trainId != null && trainId > 0) {
			   train.setState(2);//已核对
			   result = trainService.editTrain(train);
		   }else {
			   result = trainService.addTrain(train);
		   }
	   }
		
	   map.put("success", result>0);
	   if(result>0) {
		   map.put("message", "保存成功");
	   }else {
		   map.put("message", "保存失败！！！");
	   }
	   
	   return map;
    }
 
	@RequestMapping("/info")
	public ModelAndView trainInfo(HttpServletRequest request, HttpServletResponse response,Integer trainId) throws IOException {
		ModelAndView mav = new ModelAndView();
		if(trainId != null && trainId > 0) {
			TrainModel result = trainService.getInfoById(trainId);
			mav.addObject("train", result);
		}
		
		mav.setViewName("/train/info");
		return mav;
	}

 	@RequestMapping("/isExist")
 	 public @ResponseBody Map<String, Object> isExist(HttpServletRequest httpRequest, HttpServletResponse httpResponse,String trainName) {
		   Map<String, Object> map = new HashMap<String, Object>();
		   TrainModel oldTrain = new TrainModel();
		   if(trainName != null && !" ".equals(trainName)) {
			    oldTrain = trainService.getByTrainName(trainName);
			   if(oldTrain != null) {
				   map.put("oldTrain", oldTrain);
			   }
		   }
		   
		   map.put("success", oldTrain == null);
		   return map;
 	}
 	
 	
	@RequestMapping("/getTracksByDireId")
    public @ResponseBody Map<String, Object> getTracksByDireId(HttpServletRequest httpRequest, HttpServletResponse httpResponse,Integer comeDireId,Integer goDireId) {
	   Map<String, Object> map = new HashMap<String, Object>();
	   List<TrackModel> trackList = new ArrayList<TrackModel>();
	   
	   if(comeDireId != null && goDireId != null) {
		   map.put("comeId", comeDireId);
		   map.put("goId", goDireId);
		   RelationDirectionModel directionModel = relationDirectionService.getByMap(map);
		   if(directionModel != null) {
			   String ableTrace = directionModel.getAbleTrace();
			   List<String> trackIdList = Arrays.asList(ableTrace.split(","));
			   if(trackIdList != null && trackIdList.size() >0) {
				   for(String temId : trackIdList) {
					   TrackModel track = trackService.getByTrackId(Integer.valueOf(temId));
					   trackList.add(track);
				   }
			   }
		   }
	   }
	   
	   if(comeDireId != null && goDireId == 0) {
		   List<ComeGoDirectionModel> goDirectionList = new ArrayList<ComeGoDirectionModel>(); 
		   List<Integer> goIdList = relationDirectionService.listGoIdByComeId(comeDireId);
		   if(goIdList != null && goIdList.size() >0) {
			   goDirectionList = comeGoService.listByIdS(goIdList);
		   }
		   map.put("goDirectionList", goDirectionList);
	   }
	   
	   map.put("success", trackList.size()>0);
	   map.put("trackList", trackList);
	   return map;
    }
			
	@RequestMapping("/deleteAll")
	 public @ResponseBody Map<String, Object> deleteAll(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		   Map<String, Object> map = new HashMap<String, Object>();
		   HttpSession session = httpRequest.getSession();
		   UserModel user = (UserModel) session.getAttribute("user");
		   logger.info("-------------" + user.getUserName() + "-----删除旧数据-------------");
		   int result = trainService.deleteAll();
		   if(result >0) {
			   	map.put("success", true);
				map.put("message", "删除成功~");
		   }else {
			   map.put("success", false);
			   map.put("message", "删除失败，请重试！");
		   }
		   return map;
	}
	
	
	/*@RequestMapping("/getInfo4Work")
    public @ResponseBody Map<String, Object> getInfo4Work(HttpServletRequest request, HttpServletResponse response,Integer trainId) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		if(trainId != null && trainId >0) {
			TrainModel train = trainService.getInfoById(trainId);
			List<TrackModel> pickUpTrackList = new ArrayList<TrackModel>(); //接车股道
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			String stareTimeStr = sdf.format(train.getStartTime());
			Date startTime = (Date) sdf.parse(stareTimeStr);
			train.setStartTime(startTime);
			Map<String, Object> map2 = new HashMap<String,Object>();
			if(train.getComeDirectionId() != null && train.getGoDirectionId() != null) {
				   map2.put("comeId", train.getComeDirectionId());
				   map2.put("goId", 0);
				   RelationDirectionModel directionModel = relationDirectionService.getByMap(map2);
				   if(directionModel != null) {
					   String ableTrace = directionModel.getAbleTrace();
					   List<String> trackIdList = Arrays.asList(ableTrace.split(","));
					   if(trackIdList != null && trackIdList.size() >0) {
						   for(String temId : trackIdList) {
							   TrackModel track = trackService.getByTrackId(Integer.valueOf(temId));
							   pickUpTrackList.add(track);
						   }
					   }
				   }
			}
			
			List<TrackModel> departureTrackList = new ArrayList<TrackModel>(); //发车股道
			Map<String, Object> map3 = new HashMap<String,Object>();
			if(train.getComeDirectionId() != null && train.getGoDirectionId() != null) {
				   map3.put("comeId", train.getComeDirectionId());
				   map3.put("goId", train.getGoDirectionId());
				   RelationDirectionModel directionModel = relationDirectionService.getByMap(map3);
				   if(directionModel != null) {
					   String ableTrace = directionModel.getAbleTrace();
					   List<String> trackIdList = Arrays.asList(ableTrace.split(","));
					   if(trackIdList != null && trackIdList.size() >0) {
						   for(String temId : trackIdList) {
							   TrackModel track = trackService.getByTrackId(Integer.valueOf(temId));
							   departureTrackList.add(track);
						   }
					   }
				   }
			}
			
			ComeGoDirectionModel comeDirec = comeGoService.getByDirecid(train.getComeDirectionId());
			ComeGoDirectionModel goDirec = comeGoService.getByDirecid(train.getGoDirectionId());
			
			map.put("train", train);
			map.put("pickUpTrackList", pickUpTrackList);
			map.put("departureTrackList", departureTrackList);
			map.put("comeDirec", comeDirec);
			map.put("goDirec", goDirec);
			map.put("success", true);
		}else {
			map.put("success", false);
		}
	   
	   return map;
	}
	*/
	
	
	@RequestMapping("/fileUpload")
	 public @ResponseBody Map<String, Object> fileUpload(HttpServletRequest request, HttpServletResponse httpResponse,@RequestParam("file") MultipartFile file){
		long  startTime=System.currentTimeMillis();
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("-------------用户：" + user.getUserName() + "------上传文件-------------");
		if(file != null) {
			String fileName = file.getOriginalFilename(); //文件的原名
			String type = file.getContentType();
			logger.info("fileName====" + fileName + "************* fileType====="  + type+"*********  name==="+file.getName());
			Workbook wb = null;
			
			try {
				InputStream in = file.getInputStream();
				logger.info("-------判断Excel的版本,获取Workbook-------");
				if(fileName.endsWith(".xls")){     //Excel2003
					wb = new HSSFWorkbook(in);
				}else if(fileName.endsWith(".xlsx")){    // Excel2007/2010
					wb = new XSSFWorkbook(in);
				}else {
					map.put("success", false);
					map.put("message", "请上传excle文件");
					return map;
				}
				
				/*//提取车站名称
				Set<String> stationSet = ExcelUtil.pickUpStationName(wb);
				if(stationSet != null && stationSet.size() > 0) {
					for(String temName : stationSet) {
						StationModel temStation = stationService.getByName(temName);
						if(temStation != null && temStation.getStationId() > 0) {
							map.put("success", true);
							map.put("message", "上传成功");
							continue;
						}else {
							StationModel station = new StationModel();
							station.setStationName(temName);
							station.setState(1);
							Integer result = stationService.saveStation(station);
							if(result > 0) {
								map.put("success", true);
								map.put("message", "上传成功");
							}
						}
					}
				}*/
				
				
				//提取经过郑州京广场的车次
				List<TrainModel> trainList = ExcelUtil.readExcel(wb);
				if(trainList != null && trainList.size() > 0) {
					Integer result = trainService.addTrainByExcel(trainList);
					if(result > 0) {
						map.put("success", true);
						map.put("message", "上传成功");
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("message", e.getMessage());
				return map;
			}
		}else {
			map.put("success", false);
			map.put("message", "请上传文件");
			return map;
		}
     
		long  endTime=System.currentTimeMillis();
		System.out.println("方法运行时间："+String.valueOf(endTime-startTime)+"ms");
		return map;
	}
	
	
	
}
